"""
# 特征缩放/归一化
"""
import pandas as pd
import numpy as np
import sklearn.preprocessing as preproc
import matplotlib.pyplot as plt

# 特征缩放示例
# 加载在线新闻流行度数据集
news_df = pd.read_csv('../数据集/OnlineNewsPopularity.csv', delimiter=',', header=0)
print(np.array(news_df[' n_tokens_content']))

# min-max缩放
news_df['min-max'] = preproc.minmax_scale(news_df[[' n_tokens_content']])
print(np.array(news_df['min-max']))
# 标准化——注意根据标准化的定义，有些结果会是负的
news_df['standardized'] = preproc.StandardScaler().fit_transform(news_df[[' n_tokens_content']])
print(np.array(news_df['standardized']))
# L2-归一化
news_df['l2-normalized'] = preproc.normalize(news_df[[' n_tokens_content']], axis=0)
print(np.array(news_df['l2-normalized']))
# 绘制原始数据和缩放后数据的直方图
fig, (ax_orig, ax_minmax, ax_std, ax_normal) = plt.subplots(4, 1)
fig.tight_layout()

news_df[' n_tokens_content'].hist(ax=ax_orig, bins=100)
ax_orig.tick_params(labelsize=14)
ax_orig.set_xlabel('Article word count', fontsize=14)
ax_orig.set_ylabel('')

news_df['min-max'].hist(ax=ax_minmax, bins=100)
ax_minmax.tick_params(labelsize=14)
ax_minmax.set_xlabel('Min-max scaled word count', fontsize=14)
ax_minmax.set_ylabel('')

news_df['standardized'].hist(ax=ax_std, bins=100)
ax_std.tick_params(labelsize=14)
ax_std.set_xlabel('Standardized word count', fontsize=14)
ax_std.set_ylabel('')

news_df['l2-normalized'].hist(ax=ax_normal, bins=100)
ax_normal.tick_params(labelsize=14)
ax_normal.set_xlabel('L2-normalized word count', fontsize=14)
ax_normal.set_ylabel('')

plt.savefig('./可视化/原始数据和缩放后数据的直方图.png')
plt.show()